//
//  BFBaseProgressLayer.swift
//  CALayerDemo
//
//  Created by HJQ on 2018/7/14.
//  Copyright © 2018年 HJQ. All rights reserved.
//

import UIKit

// MARK: - 圆环的基类
class BFBaseProgressLayer: CALayer {

    var number: Double = 0.0 {
        didSet {
            self.textLayer.string = String.init(format: "%.0f%%", number * 100)
            self.textLayer.setNeedsDisplay()
            self.setNeedsDisplay()
        }
    }

    // 1.文本
    lazy var textLayer: CATextLayer = {
        let layer = CATextLayer()
        let font = UIFont.systemFont(ofSize: 12)
        layer.font = font.fontName as CFTypeRef
        layer.fontSize = font.pointSize
        layer.foregroundColor = UIColor.black.cgColor
        layer.alignmentMode = kCAAlignmentCenter
        layer.contentsScale = UIScreen.main.scale
        // 不设置会失帧（防止失帧）
        layer.isWrapped = true
        layer.string = ""
        return layer
    }()

    override init() {
        super.init()
        addSublayer(textLayer)
    }

    override init(layer: Any) {
        super.init(layer: layer)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func layoutSublayers() {
        super.layoutSublayers()

        // 计算文本的高度
        let textHeight = NSString.init(string: "100%").boundingRect(with: CGSize.init(width: CGFloat.infinity, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)], context: nil).height
        let y = (self.frame.height - textHeight) / 2.0
        let w = self.frame.width
        self.textLayer.frame = CGRect.init(x: 0, y: y, width: w, height: textHeight)

    }
}
